import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Balloon, Tag, Button } from '@teamix/ui';
import { YunxiaoIcon, YunxiaoTable, Section, ButtonIcon } from '@alife/devops-ui';
import BalloonConfirm from 'components/ballonConfirm';
import ProtectedModal from './protectedModal/index';
import CONSTANTS from 'utils/constants.js';
import ListEmpty from 'atComponents/ListEmpty';
import intl from '../../../../../../../../../locale';
import docs from 'utils/docs';

const { testNames } = CONSTANTS.ENUM;
export default class BaseForm extends Component {
  static propTypes = {
    protectedBranches: PropTypes.arrayOf(PropTypes.object),
    defaultBranch: PropTypes.string,
    onChange: PropTypes.func,
  };

  static defaultProps = {
    protectedBranches: [],
    defaultBranch: '',
    onChange: () => {},
  };

  state = {
    submitting: false,

    tableJSX: [
      {
        title: intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.BranchRule',
          defaultMessage: '分支规则',
        }),
        dataIndex: 'branch',
        cell: (value, index, record) => {
          return (
            <div>
              {value}
              {value === this.props.curDefaultBranch && (
                <Tag className="ml10">
                  {intl.get({
                    id: 'code-assets.settingsBranches.containers.protectedBranchesForm.DefaultBranch',
                    defaultMessage: '默认分支',
                  })}
                </Tag>
              )}

              {!!record.matches &&
                (record.matches.length > 0 ? (
                  <Balloon.Tooltip
                    trigger={
                      <div>
                        <Tag className="ml10">
                          {record.matches.length}
                          {intl.get({
                            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.MatchingBranches',
                            defaultMessage: '个匹配分支',
                          })}
                        </Tag>
                      </div>
                    }
                    align={'t'}
                  >
                    <div>
                      {record.matches.map((item) => {
                        return <div>{item}</div>;
                      })}
                    </div>
                  </Balloon.Tooltip>
                ) : null)}
            </div>
          );
        },
      },

      {
        title: intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.PushAllowed',
          defaultMessage: '允许推送',
        }),
        dataIndex: 'allow_push',
        cell: (value, index) => {
          const allowPushResult = this.getRoles(value, '+', index, 'allow_push_users');
          const hasUsers = allowPushResult?.users?.length > 0;
          const allPushPerson = (
            <div
              className="table-cell-one-line"
              style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
            >
              {allowPushResult.role && <div>{`角色：${allowPushResult.role}`}</div>}
              {hasUsers && <div>{`用户：${allowPushResult.users.join('、')}`}</div>}
            </div>
          );
          const trigger = (
            <div className="table-cell-one-line">
              <span>{allowPushResult.role}</span>
              <span>
                {hasUsers &&
                  `${allowPushResult.role && '+'}${allowPushResult?.users?.length}个用户`}
              </span>
            </div>
          );
          return (
            <Balloon.Tooltip trigger={allowPushResult === 'allEmpty' ? '无' : trigger} align={'t'}>
              {allowPushResult === 'allEmpty' ? '无' : allPushPerson}
            </Balloon.Tooltip>
          );
        },
        className: 'allow-push-col',
      },

      {
        title: intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.MergeAllowed',
          defaultMessage: '允许合并',
        }),
        dataIndex: 'allow_merge',
        cell: (value, index) => {
          const allowMergeResult = this.getRoles(value, '+', index, 'allow_merge_users');
          const hasUsers = allowMergeResult?.users?.length > 0;
          const allowMergePerson = (
            <div
              className="table-cell-one-line"
              style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
            >
              {allowMergeResult.role && <div>{`角色：${allowMergeResult.role}`}</div>}
              {hasUsers && <div>{`用户：${allowMergeResult.users.join('、')}`}</div>}
            </div>
          );
          const trigger = (
            <div className="table-cell-one-line">
              <span>{allowMergeResult.role}</span>
              <span>
                {hasUsers &&
                  `${allowMergeResult.role && '+'}${allowMergeResult?.users?.length}个用户`}
              </span>
            </div>
          );
          return (
            <Balloon.Tooltip trigger={allowMergeResult === 'allEmpty' ? '无' : trigger} align={'t'}>
              {allowMergeResult === 'allEmpty' ? '无' : allowMergePerson}
            </Balloon.Tooltip>
          );
        },
        className: 'allow-merge-col',
      },

      {
        title: intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.MergeRules',
          defaultMessage: '合并规则',
        }),
        dataIndex: 'merge_request',
        className: 'merge-request-col',
        cell: (value, index, record) => {
          const text = this.getMrText(record);
          if (!text.length) {
            return intl.get({
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.No',
              defaultMessage: '无',
            });
          }
          return (
            <Balloon.Tooltip
              trigger={<div className="table-cell-one-line">{text.join(';')}</div>}
              align={'t'}
            >
              <div style={{ width: '250px' }}>
                {text.map((item) => {
                  return <div>{item}</div>;
                })}
              </div>
            </Balloon.Tooltip>
          );
        },
      },

      {
        title: intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Operation',
          defaultMessage: '操作',
        }),
        dataIndex: 'rules',
        // align: 'center',
        width: '160px',
        cell: (value, index, record) => {
          return (
            <div>
              <Button
                type="primary"
                text
                size="small"
                className="edit-btn"
                onClick={() => {
                  this.showModal('edit', record);
                }}
              >
                {intl.get({
                  id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Editing',
                  defaultMessage: '编辑',
                })}
              </Button>
              <BalloonConfirm
                type="warning"
                align="br"
                title={intl.get({
                  id: 'code-assets.settingsBranches.containers.protectedBranchesForm.ConfirmDeletion',
                  defaultMessage: '确认删除',
                })}
                content={intl.get(
                  {
                    id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AreYouSureYouWant',
                    defaultMessage: '确认需要删除 {recordBranch} 保护分支吗？',
                  },
                  { recordBranch: record.branch },
                )}
                triggerType="click"
                trigger={
                  <Button type="primary" text size="small">
                    {intl.get({
                      id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Delete',
                      defaultMessage: '删除',
                    })}
                  </Button>
                }
                okFn={() => {
                  this.deleteProtectedBranch(record);
                }}
                confirmProps={{ loading: this.state.submitting }}
              />
            </div>
          );
        },
      },
    ],
  };

  showModal = (type, record) => {
    this.props.updateData({
      isModalOpen: true,
      record:
        type === 'edit'
          ? JSON.parse(JSON.stringify(record))
          : {
              branch: '',
              allow_merge: [40, 30],
              allow_push: [40, 30],
              test_names: [],
              merge_request: {
                required: false,
                mr_mode: 'general',
                allow_self_approval: false,
                minimum_approval: 1,
                default_assignees: [],
                allow_merge_request: [40, 30],
              },

              test_setting: {},
            },

      modalType: type,
    });
  };

  getRoles = (value, split = '', index, type) => {
    const { roles, protectedBranches } = this.props;
    let text = '';
    if (type === 'allow_merge_users' || type === 'allow_push_users') {
      if ((!value || !value.length) && protectedBranches[index][type].length === 0) {
        return 'allEmpty';
      } else {
        roles.forEach((role) => {
          if (value.indexOf(role.value) > -1) {
            text += text ? split + role.label : role.label;
          }
        });
        return {
          role: text,
          users: protectedBranches[index][type].map((user) => user.name),
        };
      }
    }
    if (!value || !value.length) {
      return intl.get({
        id: 'code-assets.settingsBranches.containers.protectedBranchesForm.No',
        defaultMessage: '无',
      });
    }
    roles.forEach((role) => {
      if (value.indexOf(role.value) > -1) {
        text += text ? split + role.label : role.label;
      }
    });
    return text;
  };

  getTestNames = (test_setting) => {
    const data = [];
    if (!test_setting || !test_setting.required) {
      return data;
    }

    const keys = Object.keys(test_setting).filter((item) => {
      return !!(test_setting[item] && test_setting[item].enabled);
    });
    testNames.forEach((item) => {
      if (keys.includes(item.key)) {
        data.push(item.label);
      }
    });
    if (
      test_setting.check_config &&
      test_setting.check_config.check_items &&
      test_setting.check_config.check_items.some((item) => item.required)
    ) {
      data.push('流水线检测');
    }
    return data;
  };

  getSelfApproval = (mr) => {
    if (!mr.required) {
      return '';
    }
    return mr.allow_self_approval
      ? intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Is',
          defaultMessage: '是',
        })
      : intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.No.2',
          defaultMessage: '否',
        });
  };

  getRequireDiscussionProcessed = (mr) => {
    if (!mr.required) {
      return '';
    }
    return mr.is_require_discussion_processed
      ? intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Is',
          defaultMessage: '是',
        })
      : intl.get({
          id: 'code-assets.settingsBranches.containers.protectedBranchesForm.No.2',
          defaultMessage: '否',
        });
  };

  getMrText = (record) => {
    const mr = record.merge_request;
    const { test_setting } = record;
    if (!mr || !test_setting || (!mr.required && !test_setting.required)) {
      return [];
    }
    const selfApproval = this.getSelfApproval(mr);
    const requireDiscussionProcessed = this.getRequireDiscussionProcessed(mr);
    const testNamesStr = this.getTestNames(record.test_setting).join('、');
    if (mr.required) {
      let text = [];
      if (mr.mr_mode !== 'general') {
        text = [
          mr.required
            ? intl.get({
                id: 'code-assets.settingsBranches.containers.protectedBranchesForm.ReviewModeCodeowner',
                defaultMessage: '评审模式：CodeOwner',
              })
            : intl.get({
                id: 'code-assets.settingsBranches.containers.protectedBranchesForm.ReviewMode',
                defaultMessage: '评审模式：',
              }),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AllowCreatorPassSelfapproval',
              defaultMessage: '允许创建者通过：{selfApproval}',
            },
            { selfApproval },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AllRequestedCommentsResolvedRequirediscussionprocessed',
              defaultMessage: '要求评论全部已解决：{requireDiscussionProcessed}',
            },
            { requireDiscussionProcessed },
          ),
        ];
      } else {
        const defaultAssigneesArr = mr.default_assignees
          ? mr.default_assignees.map((item) => {
              return item.name;
            })
          : [];
        const white_list = mr.white_list
          ? intl.get({
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Set',
              defaultMessage: '已设置',
            })
          : intl.get({
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.NotSet',
              defaultMessage: '未设置',
            });
        const allow_merge_request_roles = this.getRoles(mr.allow_merge_request, '、');
        const defaultAssigneesStr = defaultAssigneesArr.join('、');
        text = [
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AllowMergeRequestsAllowmergerequest',
              defaultMessage: '允许通过合并请求：{allowMergeRequest}',
            },
            { allowMergeRequest: allow_merge_request_roles },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.MinimumNumberOfReviewersMrminimumapproval',
              defaultMessage: '最少通过评审人：{mrMinimumApproval}',
            },
            { mrMinimumApproval: mr.minimum_approval },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.DefaultReviewerDefaultassigneesstr',
              defaultMessage: '默认评审者：{defaultAssigneesStr}',
            },
            { defaultAssigneesStr },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.ReviewFileWhitelistWhitelist',
              defaultMessage: '评审文件白名单: {whiteList}',
            },
            { whiteList: white_list },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AllowCreatorPassSelfapproval',
              defaultMessage: '允许创建者通过：{selfApproval}',
            },
            { selfApproval },
          ),
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AllRequestedCommentsResolvedRequirediscussionprocessed',
              defaultMessage: '要求评论全部已解决：{requireDiscussionProcessed}',
            },
            { requireDiscussionProcessed },
          ),
        ];
      }
      if (test_setting.required) {
        text.push(
          intl.get(
            {
              id: 'code-assets.settingsBranches.containers.protectedBranchesForm.RunTheTestnamesstrCommandAutomatically',
              defaultMessage: '需要通过自动化执行：{testNamesStr}',
            },
            { testNamesStr },
          ),
        );
      }
      return text;
    } else {
      return [
        intl.get(
          {
            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.RunTheTestnamesstrCommandAutomatically',
            defaultMessage: '需要通过自动化执行：{testNamesStr}',
          },
          { testNamesStr },
        ),
      ];
    }
  };
  deleteProtectedBranch = (record) => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.props.unprotectedBranch(record, () => {
      this.setState({ submitting: false });
    });
  };

  renderTableCell = (value, index, record, type) => {
    if (type === 'push') {
      return (
        <div>
          {intl.get({
            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.AdministratorDeveloper',
            defaultMessage: '管理员+开发者',
          })}
        </div>
      );
    }
    if (type === 'merge') {
      return (
        <div>
          {intl.get({
            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.Administrator',
            defaultMessage: '管理员',
          })}
        </div>
      );
    }
    if (
      type ===
      intl.get({
        id: 'code-assets.settingsBranches.containers.protectedBranchesForm.MergeRules',
        defaultMessage: '合并规则',
      })
    ) {
      return (
        <div>
          {intl.get({
            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.CodeownerMode',
            defaultMessage: 'codeowner模式',
          })}
        </div>
      );
    }
    if (type === 'actions') {
      return (
        <div>
          <YunxiaoIcon type="edit-line" /> <YunxiaoIcon type="delete-line" />
        </div>
      );
    }
  };

  render() {
    const { protectedBranches, isLoadingTable, isModalOpen } = this.props;
    const { tableJSX } = this.state;
    return (
      <React.Fragment>
        <Section
          title={
            <>
              {intl.get({
                id: 'code-assets.settingsBranches.containers.protectedBranchesForm.BranchProtectionRules',
                defaultMessage: '保护分支规则',
              })}
              <Balloon
                closable={false}
                trigger={
                  <ButtonIcon
                    name="question-line"
                    style={{ marginLeft: 4, display: 'inline-block' }}
                  />
                }
                align="t"
              >
                <a href={docs('branchSettings')} target="_blank" rel="noreferrer">
                  {intl.get({
                    id: 'code-assets.settingsBranches.containers.protectedBranchesForm.HowToSetBranchProtection',
                    defaultMessage: '如何设置保护分支规则',
                  })}
                </a>
              </Balloon>
            </>
          }
          description={intl.get({
            id: 'code-assets.settingsBranches.containers.protectedBranchesForm.ProtectingABranchEnsuresThe',
            defaultMessage: '保护分支会保障分支安全性，不允许任何角色进行强制推送及删除',
          })}
          operation={
            <Button
              type="primary"
              text
              onClick={() => {
                this.showModal('add');
              }}
            >
              <YunxiaoIcon type="add-fill" />
              <span>
                {intl.get({
                  id: 'code-assets.settingsBranches.containers.protectedBranchesForm.CreateAProtectionBranchRule',
                  defaultMessage: '新建保护分支规则',
                })}
              </span>
            </Button>
          }
        >
          <div className="protect-form">
            <div className="branches-table">
              {isLoadingTable || protectedBranches.length ? (
                <YunxiaoTable hasBorder dataSource={protectedBranches} loading={isLoadingTable}>
                  {tableJSX.map((item) => {
                    return (
                      <YunxiaoTable.Column
                        {...item}
                        key={item.dataIndex}
                        className={`branches-table-item ${item.className || ''}`}
                      />
                    );
                  })}
                </YunxiaoTable>
              ) : (
                <ListEmpty
                  type="card"
                  size="small"
                  content="暂无规则"
                  image="none"
                  className="no-content no-btns"
                />
              )}
            </div>
          </div>
          {isModalOpen ? <ProtectedModal {...this.props} /> : null}
        </Section>
      </React.Fragment>
    );
  }
}
